import axios from 'axios';

// 创建axios实例
const apiClient = axios.create({
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 避免在登录页面重复跳转
    const isLoginPage = window.location.pathname === '/login';
    
    if (error.response?.status === 401 && !isLoginPage) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    
    // 记录错误信息用于调试
    console.error('API请求错误:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      message: error.message,
      data: error.response?.data
    });
    
    return Promise.reject(error);
  }
);

// 定义影视推荐相关接口
const recommendationService = {
  async getHotMovies(limit = 20) {
    try {
      const response = await apiClient.get(
        '/api/v1/recommendation/hot-movies',
        { params: { limit } }
      );
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '加载热映电影失败' 
      };
    }
  },
  async getUpcomingMovies(limit = 20) {
    try {
      const response = await apiClient.get(
        '/api/v1/recommendation/coming-soon-movies',
        { params: { limit } }
      );
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '加载即将上映电影失败' 
      };
    }
  },
  async getMovieDetail(movie_id, source = null) {
    try {
      let url = `/api/v1/recommendation/movie-detail/${movie_id}`;
      if (source) {
        url += `?source=${source}`;
      }
      const response = await apiClient.get(url);
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '获取电影详情失败' 
      };
    }
  },
  
  async getPersonalizedRecommendations() {
    try {
      const response = await apiClient.get('/api/v1/recommendation/personalized');
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '获取个性化推荐失败' 
      };
    }
  },
  
  async clearPersonalizedCache() {
    try {
      const response = await apiClient.delete('/api/v1/recommendation/personalized/cache');
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '清除个性化推荐缓存失败' 
      };
    }
  },
  
  async getUserProfileData() {
    try {
      const response = await apiClient.get('/api/v1/auth/profile-data');
      return { success: true, data: response.data };
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.detail || '获取用户画像失败' 
      };
    }
  }
};

export default recommendationService;